<?php
/***********************************************
 * @package	core
 * @desc 	标志字符二进制化
 ***********************************************/
namespace classlib\imsdk;
class binproc {
	const BYTESIZE 		= 255;
	const SHTINTSIZE	= 65535;
	const INTSIZE       = 2147483647;
	private $start		= 0;
	private $binstr     = '';
	
	public function __construct() {
		$this->__init__('');
	}
	
	public function __init__($str) {
		$this->binstr   = $str;
		$this->start    = 0;
	}
	
	public function read_byte() {
		$chr = substr($this->binstr, $this->start, 1);
		$this->start += 1;
		return ord($chr);
	}
	
	public function read_sint() {
		$data = substr($this->binstr, $this->start, 2);
		$data = unpack("n", $data);
		$this->start += 2;
		return (isset($data[1])? $data[1]:FALSE);
	}
	
	public function read_int() {
		$data = substr($this->binstr, $this->start, 4);
		$data = unpack("N", $data);
		$this->start += 4;
		return (isset($data[1])? $data[1]:FALSE);
	}
	
	public function read_float() {
		$data = substr($this->binstr, $this->start, 4);
		$data = unpack("f", $data);
		$this->start += 4;
		return (isset($data[1])? $data[1]:FALSE);
	}
	
	public function read_sstr() {
		$len  = $this->read_byte();
		if ($len === FALSE || $len > self::BYTESIZE) {
			return FALSE;
		}
		$rstr = substr($this->binstr, $this->start, $len);
		$this->start += $len;
		return $rstr;
	}
	
	public function read_str() {
		$len  = $this->read_sint();
		if ($len === FALSE || $len > self::SHTINTSIZE) {
			return FALSE;
		}
		$rstr = substr($this->binstr, $this->start, $len);
		$this->start += $len;
		return $rstr;
	}
	
	public function read_lstr() {
		$len  = $this->read_int();
		if ($len === FALSE || $len > self::INTSIZE) {
			return FALSE;
		}
		$rstr = substr($this->binstr, $this->start, $len);
		$this->start += $len;
		return $rstr;
	}
	
	public function write_byte($byte) {
		if (is_numeric($byte)) {
			return chr($byte);
		}
		return $byte;
	}
	
	//注意事项php短整形负数不能用这个压
	public function write_sint($sint) {
		return pack("n", $sint);
	}
	
	public function write_int($int) {
		return pack("N", $int);
	}
	
	public function write_float($float) {
		return pack("f", $float);
	}
	
	public function write_sstr($str) {
		$len = strlen($str);
		if ($len > self::BYTESIZE) {
			return FALSE;
		}
		return $this->write_byte($len).$str;
	}
	
	public function write_str($str) {
		$len = strlen($str);
		if ($len > self::SHTINTSIZE) {
			return FALSE;
		}
		return $this->write_sint($len).$str;
	}
	
	public function write_lstr($str) {
		$len = strlen($str);
		if ($len > self::INTSIZE) {
			return FALSE;
		}
		return $this->write_int($len).$str;
	}
}
